#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>

typedef struct msgbuf {
    long mtype;
    int id;
    char sex;
    char name[32];
    int score;
}msg_t;

int main(){
    key_t key = 0;
    int msqid = 0;
    if(-1 == (key = ftok("/home/linux", 'A'))){
        perror("ftok error");
        exit(-1);
    }
    printf("key = %#x\n", key);
    
    if(-1 == (msqid = msgget(key, IPC_CREAT | 0666))){
        perror("msgget error");
        exit(-1);
    }

    msg_t msg1 = {
        .mtype = 10,
        .id = 1001,
        .sex = 'm',
        .name = "zhangsan",
        .score = 98
    };
    msgsnd(msqid, &msg1, sizeof(msg1)-sizeof(long), 0);
    msg_t msg2 = {
        .mtype = 20,
        .id = 1002,
        .sex = 'w',
        .name = "lisi",
        .score = 99
    };
    msgsnd(msqid, &msg2, sizeof(msg2)-sizeof(long), 0);

    //获取消息队列属性
    struct msqid_ds mds;
    msgctl(msqid, IPC_STAT, &mds);
    printf("key = %#x\n", mds.msg_perm.__key);
    printf("msg num = %ld\n", mds.msg_qnum);
    printf("msg bytes = %ld\n", mds.__msg_cbytes);
    printf("max bytes= %ld\n", mds.msg_qbytes);
    printf("mode = %#o\n", mds.msg_perm.mode);
    printf("uid = %d\n", mds.msg_perm.uid);
    printf("gid = %d\n", mds.msg_perm.gid);
    
    puts("----------------------------");
    mds.msg_qbytes = 32 * 1024;//改小可以，改大需要特权 sudo  man手册有说明
    msgctl(msqid, IPC_SET, &mds);
    puts("----------------------------");

    msgctl(msqid, IPC_STAT, &mds);
    printf("key = %#x\n", mds.msg_perm.__key) ;
    printf("msg num = %ld\n", mds.msg_qnum);
    printf("msg bytes = %ld\n", mds.__msg_cbytes);
    printf("max bytes= %ld\n", mds.msg_qbytes);
    printf("mode = %#o\n", mds.msg_perm.mode);
    printf("uid = %d\n", mds.msg_perm.uid);
    printf("gid = %d\n", mds.msg_perm.gid);

    //删除消息队列
    msgctl(msqid,IPC_RMID,NULL);

    return 0;
}